<script setup>
import request from '@/utils/request'

import { getToken } from '@/utils/auth'

import useSettingsStore from '@/store/modules/settings'

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + props.importUrl)

const { proxy } = getCurrentInstance()

const emit = defineEmits()

const props = defineProps({
  // 是否开启
  isShow: {
    type: Boolean,
    default: false
  },
  // 导入接口
  importUrl: {
    type: String,
    default: ''
  },
  // 模板接口
  templateUrl: {
    type: String,
    default: ''
  },
  // 数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'xlsx']
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
})

// 文件路径
const file = ref('')

const headers = ref({ Authorization: 'Bearer ' + getToken() })

const fileList = ref([])

// 关闭
const close = () => {
  file.value = ''
  fileList.value = []
  emit('update:isShow', false)
  emit('close')
}

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.')
    const fileExt = fileName[fileName.length - 1]
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`)
      return false
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(`导入文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  proxy.$modal.loading('正在导入文件，请稍候...')
  return true
}

// 成功
const success = res => {
  if (res.code !== 200) {
    proxy.$modal.closeLoading()
    proxy.errorMsg(res.msg + ' ==>请重新整理数据再次导入！')
    fileList.value = []
    return
  }
  proxy.$modal.closeLoading()
  proxy.successMsg('导入成功！')
  close()
}

// 失败
const error = err => {
  proxy.$modal.closeLoading()
  proxy.errorMsg('导入失败！==>' + err)
}
</script>

<template>
  <p-XiaoheDialog :dialogVisible="props.isShow" :title="`${useSettingsStore().title}导入`" @close="close" width="30rem">
    <template #body>
      <el-form label-width="120px">
        <el-form-item label="请下载导入模板">
          <el-link
            type="primary"
            @click="
              proxy.download(templateUrl, {
                ...query,
                idStr: Ids ? Ids.join(',') : ''
              })
            "
            >{{ `下载${useSettingsStore().title}模板` }}</el-link
          >
        </el-form-item>
        <el-form-item label="导入文档">
          <el-upload
            :headers="headers"
            :action="uploadFileUrl"
            :file-list="fileList"
            @change="change"
            :limit="1"
            :before-upload="handleBeforeUpload"
            :on-success="success"
            :on-error="error"
          >
            <el-button type="primary">点击导入</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
  </p-XiaoheDialog>
</template>
<style scoped lang="scss"></style>
